<?php defined('SYSPATH') OR die('No direct access allowed.');

class Users_Controller extends Template_Controller {
    protected $restrict_guest = TRUE;
    protected $HAHAHAHAHAH;
    protected $aaaaaaa;

    public function __construct() {
        if (Router::$method == 'users_divisions') {
            $this->restrict_outside_roles = array('administrator','motivator','panitia');
        }

        parent::__construct();
    }

    public function index(){
	echo "TAMBAHANzzzzzzzz";
        url::redirect('users/page/1');
    }

    public function page($pagenum){
        $this->title .= "Home : ".$this->auth_user->name;
        $paged_users = new User_Model();

        $paging = new Pagination(array (
            'total_items' => $paged_users->count_users(),
        ));

        $this->content->pagination = $paging->render();
        $this->content->all_users = $paged_users->browse($paging->items_per_page, $paging->sql_offset);
    }

    public function view($user_id) {
        if($this->auth_user->id != $user_id && !($this->auth_user->has_role('administrator') || $this->auth_user->has_role('motivator')))
            url::redirect('home');
        $user = ORM::factory('user' , $user_id);
        if (!$user->loaded) {
            //TODO : redirect
            $this->redirect(url::site('home') , '' , 'User not exists');
        }
        else {
            $this->title = "User Details : ".$user->name;
            $this->content->user = $user;
            $this->content->group = ORM::factory('group',$user->group_id);
        }
    }

    public function edit($user_id) {
        if($this->auth_user->id != $user_id && !$this->auth_user->has_role('administrator'))
            url::redirect('home');
        else {
            //$this->content = View::factory("content/tasks");
            $user = ORM::factory('user' , $user_id);
            if (!$user->loaded) {
                $this->redirect(url::site('home') , '' , 'User not exists');
            }

            if ($_POST){
                /*$files = Validation::factory($_FILES)->add_rules('userfile','upload::valid','upload::required', 'upload::type[gif,jpg,png]', 'upload::size[1M]');
                if($files->validate()){
                    $filename = upload::save('userfile');

                    Image::factory($filename)->save('upload/'.basename($filename));
                }*/
                if($_FILES['userfile']['type'] == 'image/jpeg' || $_FILES['userfile']['type'] == 'image/gif' || $_FILES['userfile']['type'] == 'image/png'){
                    if(!is_dir('upload/'.$user->nim_fakultas))
                        mkdir('upload/'.$user->nim_fakultas);

                    $uploaddir = 'upload/'.$user->nim_fakultas.'/';
                    $basename = basename($_FILES['userfile']['name']);
                    $pointpos = strrpos($basename,'.');
                    $extension = substr($basename,$pointpos,strlen($basename)-$pointpos);
                    $uploadfile = $uploaddir.$user->nim_fakultas.'-'.$user->name.$extension;

                    move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile);

                    $user->photo = $uploadfile;
                }

                $user->e                = $_POST['e'];
                $user->i                = $_POST['i'];
                $user->s                = $_POST['s'];
                $user->n                = $_POST['n'];
                $user->t                = $_POST['t'];
                $user->f                = $_POST['f'];
                $user->j                = $_POST['j'];
                $user->p                = $_POST['p'];
                $user->name             = $_POST['name'];
                $user->gender           = $_POST['gender'];
                $user->agama            = $_POST['agama'];
                $user->nickname         = $_POST['nickname'];
                $user->nim_fakultas     = $_POST['nim_fakultas'];
                $user->nim_prodi        = $_POST['nim_prodi'];
                $user->birth_place      = $_POST['birth_place'];
                $user->birth_date       = date("Y-m-d", mktime(0, 0, 0, $_POST['month'], $_POST['day'], $_POST['year']));
                $user->hp_number        = "+62" . $_POST['hp_number'];
                $user->email            = $_POST['email'];
                $user->yahoo_id         = $_POST['yahoo_id'];
                $user->facebook_id      = $_POST['facebook_id'];
                $user->plurk_id         = $_POST['plurk_id'];
                $user->twitter_id       = $_POST['twitter_id'];
                $user->pin_bb           = $_POST['pin_bb'];
                $user->bandung_address  = $_POST['bandung_address'];
                $user->bandung_number   = $_POST['bandung_number'];
                $user->home_address     = $_POST['home_address'];
                $user->home_number      = $_POST['home_number'];
                $user->group_id         = $_POST['group'];

                if(isset($_POST['change_password_checkbox']) && isset($_POST['change_password']) && $this->auth_user->has_role('administrator'))
                    $user->password = $_POST['change_password'];

                if (isset($_POST['role'])){
                    foreach($user->roles as $role){
                        $user->remove($role);
                    }
                    $user->add(ORM::factory('role', $_POST['role']));
                    $user->add(ORM::factory('role', 'login'));
                }

                $user->save();

                $this->redirect(url::site('users/view/' . $user_id) , '' , 'User edited');
            } else {
                $this->content->day = array();
                $this->content->day[] = "Day";
                for ($i = 1; $i <= 31; $i++)
                    $this->content->day[] = $i;

                $this->content->month = array();
                $this->content->month[] = "Month";
                for ($i = 1; $i <= 12; $i++)
                    $this->content->month[] = date("M", mktime(0, 0, 0, $i, 1, 1));

                $this->content->year = array();
                $this->content->year[] = "Year";
                for ($i = date('Y')-12; $i >= date('Y')-80; $i--)
                    $this->content->year[$i] = $i;

                $this->title = "User Details";
                $this->content->user = $user;
                $groups = ORM::factory('group')->find_all();

                $this->content->groups = array();
                foreach($groups as $group){
                    $this->content->groups[$group->id] = $group->name;
                }
            }
        }
    }

    public function users_divisions($user_id){
        if(!$this->auth_user->has_role('administrator'))
            url::redirect('home');
        $user = ORM::factory('user',$user_id);
        $divisions = ORM::factory('division')->find_all();

        $this->title = "User Divisions : ".$user->name;
        $this->content->user = $user;
        $this->content->divisions = $user->divisions;

        /*Creating dropdown list (user currently division)*/
        foreach($divisions as $division){
            $dropdown_division_name[$division->id] = $division->division_name;
        }
        $this->content->dropdown_division_name = $dropdown_division_name;
        /*Creating dropdown list finish*/

        if($_POST && $this->auth_user->has_role('administrator')) {
            if(isset($_POST['selected_division_name'])) {
                Users_Controller::add_new_division($user_id, $_POST['selected_division_name']);
            }

            if(isset($_POST['checkgroup'])) {
                Users_Controller::delete_division($user_id, $_POST['checkgroup']);
            }
        }
    }

    public function user_group_members($user_id){
        $user = ORM::factory('user', $user_id);
        $users = ORM::factory('user')->where('group_id',$user->group_id)->find_all();

        $this->content->user = $user;
        $this->content->users = $users;
        $this->content->group = ORM::factory('group',$user->group_id);
    }

    public static function add_new_division($user_id, $division_id){
        $user = ORM::factory('user',$user_id);

        /*Create new array to be inserted as new division_id for user with id $user_id*/
        $i=0;
        foreach($user->divisions as $division){
            $new_division[$i++] = $division->id;
        }
        $new_division[$i] = $division_id;
        /*Create new array to be inserted finish*/

        $user->divisions = $new_division; //set the $user->divisions
        $user->save();

        url::redirect('users/users_divisions/'.$user_id);
    }

    public static function delete_division($user_id, $division_id){
        $user = ORM::factory('user',$user_id);

        $i=0;
        $new_division = array();
        foreach($user->divisions as $division){
            if(!in_array($division->id, $division_id))
                $new_division[$i++] = $division->id;
        }

        $user->divisions = $new_division;
        $user->save();

        url::redirect('users/users_divisions/'.$user_id);
    }
}
